<template>
  <div class="app-container">
    <div class="cardBox">
      <div style="display: flex" :gutter="10">
        <div style="flex: 1">
          <el-button
            @click="gobackWay"
            type="text"
            icon="el-icon-arrow-left"
            style="color: rgba(0, 0, 0, 0.85)"
            >返回</el-button
          >
          <el-divider direction="vertical"></el-divider>
          <span>{{ id ? "编辑运费模板" : "添加运费模板" }}</span>
        </div>
      </div>
    </div>
    <div
      class="cardBox"
      v-loadings="loadings"
      style="height: calc(85vh - 80px); margin-top: 20px"
    >
      <el-scrollbar
        wrap-style="overflow-x:hidden;"
        style="height: calc(73vh - 80px)"
      >
        <el-form
          :model="basicForm"
          :rules="basicRules"
          ref="basicForm"
          label-width="140px"
          class="demo-ruleForm"
        >
          <el-row>
            <el-col :span="24">
              <el-col :span="8">
                <el-form-item label-position="top" label="模板名称" prop="name">
                  <el-input
                    clearable
                    placeholder="请输入模板名称"
                    v-model="basicForm.name"
                    maxlength="20"
                    show-word-limit
                  ></el-input>
                </el-form-item>
              </el-col>
            </el-col>
            <el-col :span="24">
              <el-col :span="10">
                <el-form-item label="计费方式" prop="type">
                  <el-radio-group v-model="basicForm.type">
                    <el-radio :label="1">按件数(件)</el-radio>
                    <el-radio :label="2">按重量(kg)</el-radio>
                    <el-radio :label="3">按体积(m³)</el-radio>
                  </el-radio-group>
                </el-form-item>
              </el-col>
            </el-col>
            <el-col :span="24">
              <el-col :span="8">
                <el-form-item label="排序" prop="weight">
                  <el-input
                    clearable
                    @focus="weightFocus(basicForm)"
                    @blur="weightBlur(basicForm)"
                    placeholder="请输入排序(值越大越靠前)"
                    v-model="basicForm.weight"
                    maxlength="20"
                    show-word-limit
                  ></el-input>
                </el-form-item>
              </el-col>
            </el-col>
            <el-col :span="24">
              <el-col :span="24">
                <el-form-item label="配送地区">
                  <el-col
                    :span="24"
                    v-for="(
                      delivery_arrive, index
                    ) in basicForm.delivery_arrive"
                    :key="index"
                  >
                    <el-col :span="5" style="margin: 0 5px">
                      <el-form-item
                        label=" "
                        label-width="5px"
                        :prop="'delivery_arrive.' + index + '.region_ids'"
                        :rules="{
                          required: index == 0 ? false : true,
                          validator: index == 0 ? region_idss : region_ids,
                          trigger: 'change',
                        }"
                      >
                        <div>地区</div>
                        <el-cascader
                          :placeholder="index == 0 ? '默认全国' : '请选择地区'"
                          @change="region_ids_jsonWay(delivery_arrive)"
                          v-model="delivery_arrive.region_ids_json"
                          style="width: 100%"
                          :options="regionList"
                          collapse-tags
                          :show-all-levels="false"
                          :props="{
                            expandTrigger: 'hover',
                            multiple: true,
                            value: 'id',
                            label: 'name',
                            children: 'children',
                          }"
                          clearable
                        />
                      </el-form-item>
                    </el-col>
                    <el-col :span="4" style="margin: 0 5px">
                      <el-form-item
                        label=" "
                        label-width="5px"
                        :rules="{
                          required: true,
                          validator: first_num,
                          trigger: 'change',
                        }"
                        :prop="'delivery_arrive.' + index + '.first_num'"
                      >
                        <div>(首件/体积/重量)数量</div>
                        <el-input
                          clearable
                          @focus="Focus(delivery_arrive, 'first_num')"
                          @blur="Blur(delivery_arrive, 'first_num')"
                          placeholder="(首件/体积/重量)数量"
                          v-model="delivery_arrive.first_num"
                          maxlength="7"
                          show-word-limit
                        ></el-input>
                      </el-form-item>
                    </el-col>
                    <el-col :span="4" style="margin: 0 5px">
                      <el-form-item
                        label=" "
                        label-width="5px"
                        :rules="{
                          required: true,
                          validator: first_price,
                          trigger: 'change',
                        }"
                        :prop="'delivery_arrive.' + index + '.first_price'"
                      >
                        <div>(首件/体积/重量)价格(元)</div>
                        <el-input
                          clearable
                          @focus="Focus(delivery_arrive, 'first_price')"
                          @blur="Blur(delivery_arrive, 'first_price')"
                          placeholder="首件/体积/重量)价格(元)"
                          v-model="delivery_arrive.first_price"
                          maxlength="7"
                          show-word-limit
                        ></el-input>
                      </el-form-item>
                    </el-col>
                    <el-col :span="4" style="margin: 0 5px">
                      <el-form-item
                        label=" "
                        label-width="5px"
                        :rules="{
                          required: true,
                          validator: first_num,
                          trigger: 'change',
                        }"
                        :prop="'delivery_arrive.' + index + '.renew_num'"
                      >
                        <div>续件数量</div>
                        <el-input
                          clearable
                          @focus="Focus(delivery_arrive, 'renew_num')"
                          @blur="Blur(delivery_arrive, 'renew_num')"
                          placeholder="续件数量"
                          v-model="delivery_arrive.renew_num"
                          maxlength="7"
                          show-word-limit
                        ></el-input>
                      </el-form-item>
                    </el-col>
                    <el-col :span="4" style="margin: 0 5px">
                      <el-form-item
                        label=" "
                        label-width="5px"
                        :rules="{
                          required: true,
                          validator: first_price,
                          trigger: 'change',
                        }"
                        :prop="'delivery_arrive.' + index + '.renew_price'"
                      >
                        <div>续件价格</div>
                        <el-input
                          clearable
                          @focus="Focus(delivery_arrive, 'renew_price')"
                          @blur="Blur(delivery_arrive, 'renew_price')"
                          placeholder="续件价格(元)"
                          v-model="delivery_arrive.renew_price"
                          maxlength="7"
                          show-word-limit
                        ></el-input>
                      </el-form-item>
                    </el-col>
                    <el-col
                      v-if="basicForm.delivery_arrive.length > 1"
                      :span="1"
                      style="text-align: center"
                    >
                      <div>增/减</div>
                      <el-button
                        type="danger"
                        @click="delDistributionWay(delivery_arrive)"
                        icon="el-icon-minus"
                        circle
                      ></el-button>
                    </el-col>
                  </el-col>
                  <div>
                    <el-button
                      @click="addDistributionWay"
                      type="primary"
                      icon="el-icon-plus"
                      >添加配送区域</el-button
                    >
                  </div>
                </el-form-item>
              </el-col>
            </el-col>
            <el-col :span="24">
              <el-col :span="24">
                <el-form-item label="是否开启包邮地区" prop="is_delivery_free">
                  <el-radio-group
                    @change="is_delivery_freeWay"
                    v-model="basicForm.is_delivery_free"
                  >
                    <el-radio :label="0">关闭</el-radio>
                    <el-radio :label="1">开启</el-radio>
                  </el-radio-group>
                  <el-col
                    v-if="basicForm.is_delivery_free !== 0"
                    :span="24"
                    v-for="(delivery_free, index) in basicForm.delivery_free"
                    :key="index"
                  >
                    <el-col :span="5" style="margin: 0 5px">
                      <el-form-item
                        label=" "
                        label-width="5px"
                        :prop="'delivery_free.' + index + '.region_ids'"
                        :rules="{
                          required: true,
                          validator: region_ids,
                          trigger: 'change',
                        }"
                      >
                        <div>地区</div>
                        <el-cascader
                          @change="region_ids_jsonWay(delivery_free)"
                          v-model="delivery_free.region_ids_json"
                          style="width: 100%"
                          :options="regionList"
                          collapse-tags
                          :show-all-levels="false"
                          :props="{
                            expandTrigger: 'hover',
                            multiple: true,
                            value: 'id',
                            label: 'name',
                            children: 'children',
                          }"
                          clearable
                        />
                      </el-form-item>
                    </el-col>
                    <el-col :span="4" style="margin: 0 5px">
                      <el-form-item
                        label=" "
                        label-width="5px"
                        :rules="{
                          required: true,
                          validator: first_num,
                          trigger: 'change',
                        }"
                        :prop="'delivery_free.' + index + '.free_num'"
                      >
                        <div>包邮数量</div>
                        <el-input
                          clearable
                          @focus="Focus(delivery_free, 'free_num')"
                          @blur="Blur(delivery_free, 'free_num')"
                          placeholder="包邮数量-满多少件包邮"
                          v-model="delivery_free.free_num"
                          maxlength="7"
                          show-word-limit
                        ></el-input>
                      </el-form-item>
                    </el-col>
                    <el-col :span="4" style="margin: 0 5px">
                      <el-form-item
                        label=" "
                        label-width="5px"
                        :rules="{
                          required: true,
                          validator: first_price,
                          trigger: 'change',
                        }"
                        :prop="'delivery_free.' + index + '.free_price'"
                      >
                        <div>包邮价格</div>
                        <el-input
                          clearable
                          @focus="Focus(delivery_free, 'free_price')"
                          @blur="Blur(delivery_free, 'free_price')"
                          placeholder="包邮价格-满多少钱包邮(元)"
                          v-model="delivery_free.free_price"
                          maxlength="7"
                          show-word-limit
                        ></el-input>
                      </el-form-item>
                    </el-col>
                    <el-col
                      v-if="basicForm.delivery_free.length > 1"
                      :span="3"
                      style="text-align: center"
                    >
                      <el-button
                        type="danger"
                        @click="delFreeWay(delivery_free)"
                        icon="el-icon-minus"
                        circle
                      ></el-button>
                    </el-col>
                  </el-col>
                  <div>
                    <el-button
                      v-if="basicForm.delivery_free.length !== 0"
                      @click="addFreeWay"
                      type="primary"
                      icon="el-icon-plus"
                      >添加包邮地区</el-button
                    >
                  </div>
                </el-form-item>
              </el-col>
            </el-col>
            <el-col :span="24">
              <el-col :span="24">
                <el-form-item label="是否开启不配送地区" prop="is_delivery_not">
                  <el-radio-group
                    @change="is_delivery_notWay"
                    v-model="basicForm.is_delivery_not"
                  >
                    <el-radio :label="0">关闭</el-radio>
                    <el-radio :label="1">开启</el-radio>
                  </el-radio-group>
                  <el-col
                    v-if="basicForm.is_delivery_not !== 0"
                    :span="24"
                    v-for="(delivery_not, index) in basicForm.delivery_not"
                    :key="index"
                  >
                    <el-col :span="5" style="margin: 0 5px">
                      <el-form-item
                        label=" "
                        label-width="5px"
                        :prop="'delivery_not.' + index + '.region_ids'"
                        :rules="{
                          required: true,
                          validator: region_ids,
                          trigger: 'change',
                        }"
                      >
                        <div>地区</div>
                        <el-cascader
                          @change="region_ids_jsonWay(delivery_not)"
                          v-model="delivery_not.region_ids_json"
                          style="width: 100%"
                          :options="regionList"
                          collapse-tags
                          :show-all-levels="false"
                          :props="{
                            expandTrigger: 'hover',
                            multiple: true,
                            value: 'id',
                            label: 'name',
                            children: 'children',
                          }"
                          clearable
                        />
                      </el-form-item>
                    </el-col>
                  </el-col>
                </el-form-item>
              </el-col>
            </el-col>
          </el-row>
        </el-form>
      </el-scrollbar>
      <div style="margin-top: 30px; text-align: center">
        <el-button type="primary" @click="submitWay">保存</el-button>
      </div>
    </div>
  </div>
</template>

<script>
import {
  getFreightList,
  getFreightInfo,
  saveFreight,
  delFreight,
} from "@/api/admin/freight";
import { getRegionList } from "@/api/user/index";
export default {
  data() {
    return {
      id: "",
      loadings: true,
      regionList: [],
      basicForm: {
        id: "",
        name: "",
        type: 2,
        weight: 0,
        delivery_arrive: [
          {
            id: 0,
            region_ids: "",
            region_ids_json: [],
            first_num: "0",
            first_price: "0",
            renew_num: "0",
            renew_price: "0",
          },
        ],
        is_delivery_free: 0,
        delivery_free: [],
        is_delivery_not: 0,
        delivery_not: [],
      },
      basicRules: {
        name: [
          {
            required: true,
            validator: (rule, value, callback) => {
              let req = /[^0-9a-zA-Z\u4e00-\u9fa5]/g;
              if (!value) {
                callback(new Error("请输入模板名称"));
              } else {
                if (req.test(value)) {
                  callback(new Error("模板名称中不能存在特殊字符"));
                } else {
                  callback();
                }
              }
            },
            trigger: "change",
          },
        ],
      },
      region_ids: (rule, value, callback) => {
        if (value.length == 0) {
          callback(new Error("请选择区域"));
        } else {
          callback();
        }
      },
      region_idss: (rule, value, callback) => {
        callback();
      },
      first_num: (rule, value, callback) => {
        let req = /\D/g;
        if (value === "") {
          callback(new Error("请输入数量"));
        } else {
          if (req.test(value)) {
            callback(new Error("数量只能为数字,且只能是整数"));
          } else {
            callback();
          }
        }
      },
      first_price: (rule, value, callback) => {
        if (value === "") {
          callback(new Error("请输入价格"));
        } else {
          let req = /^\d+(\.\d{1,2})?$/;
          if (req.test(value)) {
            callback();
          } else {
            callback(new Error("只能输入数字,且只能保留两位小数"));
          }
        }
      },
    };
  },
  created() {
    const p1 = new Promise((req, rej) => {
      getRegionList({ level: 2 }).then((res) => {
        if (res.code !== 200 || res.status !== 1) {
          rej();
          this.$messages.error(res.msg);
          return;
        }
        this.regionList = res.data;
        req();
      });
    });
    var arr = [p1];
    if (this.$route.query.id) {
      this.basicForm.id = this.$route.query.id;
      const p2 = new Promise((req, rej) => {
        getFreightInfo({ id: this.$route.query.id }).then((res) => {
          if (res.code !== 200 || res.status !== 1) {
            rej();
            this.$messages.error(res.msg);
            return;
          }
          this.backups = res.data;
          req();
        });
      });
      arr = [p1, p2];
    }
    Promise.all(arr)
      .then(() => {
        if (this.$route.query.id) {
          this.getInfoWay();
        } else {
          this.loadings = false;
        }
      })
      .catch(() => {
        this.loadings = false;
      });
  },
  methods: {
    getInfoWay() {
      this.basicForm.id = this.backups.id;
      this.basicForm.name = this.backups.name;
      this.basicForm.type = Number(this.backups.type);
      this.basicForm.is_delivery_free = Number(this.backups.is_delivery_free);
      this.basicForm.is_delivery_not = Number(this.backups.is_delivery_not);
      this.basicForm.weight = this.backups.weight;
      this.basicForm.delivery_arrive = [];
      this.backups.delivery_arrive.forEach((item, index) => {
        this.basicForm.delivery_arrive.push({
          region_ids: "",
          region_ids_json: [],
          first_num: "0",
          first_price: "0",
          renew_num: "0",
          renew_price: "0",
        });
        this.basicForm.delivery_arrive[index].first_num = item.first_num;
        this.basicForm.delivery_arrive[index].first_price = item.first_price;
        this.basicForm.delivery_arrive[index].renew_num = item.renew_num;
        this.basicForm.delivery_arrive[index].renew_price = item.renew_price;
        if (item.regionList.length == 0) {
          this.basicForm.delivery_arrive[index].region_ids_json = [];
          this.basicForm.delivery_arrive[index].region_ids = "";
        } else {
          var arr = [];
          item.regionList.forEach((items, indexs) => {
            if (items.children && items.children.length !== 0) {
              items.children.forEach((itemss, indexss) => {
                arr.push([items.id, itemss.id]);
              });
            }
          });
          this.basicForm.delivery_arrive[index].region_ids_json = arr;
          this.region_ids_jsonWay(this.basicForm.delivery_arrive[index]);
        }
      });

      this.basicForm.delivery_free = [];
      this.backups.delivery_free.forEach((item, index) => {
        this.basicForm.delivery_free.push({
          region_ids: "",
          region_ids_json: [],
          free_num: "0",
          free_price: "0",
        });
        this.basicForm.delivery_free[index].free_num = item.free_num;
        this.basicForm.delivery_free[index].free_price = item.free_price;
        if (item.regionList.length == 0) {
          this.basicForm.delivery_free[index].region_ids_json = [];
          this.basicForm.delivery_free[index].region_ids = "";
        } else {
          var arr = [];
          item.regionList.forEach((items, indexs) => {
            if (items.children && items.children.length !== 0) {
              items.children.forEach((itemss, indexss) => {
                arr.push([items.id, itemss.id]);
              });
            }
          });
          this.basicForm.delivery_free[index].region_ids_json = arr;
          this.region_ids_jsonWay(this.basicForm.delivery_free[index]);
        }
      });

      this.basicForm.delivery_not = [];
      this.backups.delivery_not.forEach((item, index) => {
        this.basicForm.delivery_not.push({
          region_ids: "",
          region_ids_json: [],
        });

        if (item.regionList.length == 0) {
          this.basicForm.delivery_not[index].region_ids_json = [];
          this.basicForm.delivery_not[index].region_ids = "";
        } else {
          var arr = [];
          item.regionList.forEach((items, indexs) => {
            if (items.children && items.children.length !== 0) {
              items.children.forEach((itemss, indexss) => {
                arr.push([items.id, itemss.id]);
              });
            }
          });
          this.basicForm.delivery_not[index].region_ids_json = arr;
          this.region_ids_jsonWay(this.basicForm.delivery_not[index]);
        }
      });
      this.loadings = false;
    },
    addDistributionWay() {
      this.basicForm.delivery_arrive.push({
        id: this.basicForm.delivery_arrive.length + "" + new Date().getTime(),
        region_ids: "",
        region_ids_json: [],
        first_num: "0",
        first_price: "0",
        renew_num: "0",
        renew_price: "0",
      });
    },
    delDistributionWay(row) {
      var arr = [];
      this.basicForm.delivery_arrive.forEach((item) => {
        if (item.id !== row.id) {
          arr.push(item);
        }
      });
      this.basicForm.delivery_arrive = arr;
    },
    is_delivery_freeWay(val) {
      if (val == 1) {
        if (this.basicForm.delivery_free.length == 0) {
          this.addFreeWay();
        }
      }
    },
    addFreeWay() {
      this.basicForm.delivery_free.push({
        id: this.basicForm.delivery_free.length + "" + new Date().getTime(),
        region_ids: "",
        region_ids_json: [],
        free_num: "0",
        free_price: "0",
      });
    },
    delFreeWay(row) {
      var arr = [];
      this.basicForm.delivery_free.forEach((item) => {
        if (item.id !== row.id) {
          arr.push(item);
        }
      });
      this.basicForm.delivery_free = arr;
    },
    is_delivery_notWay(val) {
      if (val == 1) {
        if (this.basicForm.delivery_not.length == 0) {
          this.basicForm.delivery_not.push({
            id: this.basicForm.delivery_not.length + "" + new Date().getTime(),
            region_ids: "",
            region_ids_json: [],
          });
        }
      }
    },
    region_ids_jsonWay(row) {
      var arr = [];
      if (row.region_ids_json.length !== 0) {
        row.region_ids_json.forEach((item) => {
          arr.push(item[1]);
        });
        row.region_ids = arr.toString();
      } else {
        row.region_ids = "";
      }
    },
    weightFocus(item) {
      if (item.weight == 0) {
        item.weight = "";
      }
    },
    weightBlur(item) {
      if (item.weight == "") {
        item.weight = 0;
      }
      if (Number(item.weight)) {
        item.weight = Number(item.weight);
      }
    },
    Focus(item, str) {
      if (item[str] == 0) {
        item[str] = "";
      }
    },
    Blur(item, str) {
      if (item[str] == "") {
        item[str] = 0;
      }
      if (Number(item[str])) {
        item[str] = Number(item[str]);
      }
    },
    submitWay() {
      this.$refs.basicForm.validate((valid) => {
        if (valid) {
          var obj = JSON.parse(JSON.stringify(this.basicForm));
          if (obj.delivery_arrive.length == 0) {
            obj.delivery_arrive = "";
          } else {
            obj.delivery_arrive.forEach((item) => {
              item.region_ids_json = JSON.stringify(item.region_ids_json);
            });
          }

          if (obj.is_delivery_free == 0) {
            obj.delivery_free = "";
          } else {
            obj.delivery_free.forEach((item) => {
              item.region_ids_json = JSON.stringify(item.region_ids_json);
            });
          }

          if (obj.is_delivery_not == 0) {
            obj.delivery_not = "";
          } else {
            obj.delivery_not.forEach((item) => {
              item.region_ids_json = JSON.stringify(item.region_ids_json);
            });
          }
          this.loadings = true;
          saveFreight(obj).then((res) => {
            this.loadings = false;
            if (res.code !== 200 || res.status !== 1) {
              this.$messages.error(res.msg);
              return;
            }
            this.gobackWay();
          });
        } else {
          return false;
        }
      });
    },
    gobackWay() {
      this.$router.push("/admin/freight");
    },
  },
};
</script>

<style>
</style>
